package com.liuc.practice.server;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author Liu Chang
 * @Date 2021/9/13 3:18 上午
 */
public class AppClassLoader extends ClassLoader{
    public Class findClass(String fileFullName, String className) {
        byte[] bytes = null;
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        Class clazz = null;
        try {
            fis = new FileInputStream(fileFullName);
            baos = new ByteArrayOutputStream();
            int count = 0;
            while ((count = fis.read()) != -1) {
                baos.write(count);
            }
            bytes = baos.toByteArray();

            clazz = defineClass(className, bytes, 0, bytes.length);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return clazz;
    }
}
